package org.tictactoe;

import org.tictactoe.corba.GamePOA;
import org.tictactoe.corba.Step;

public class TictactoeGame extends GamePOA {
	private int[][] board;
	private int id;
	private Step lastStep;
	private boolean isStarted;
	
	public TictactoeGame(int _id) {
		id = _id;
		board = new int[3][3];
		for (int i=0; i<3; i++)
			for (int j=0; j<3; j++)
				board[i][j] = 0;
		lastStep = new Step(-1,-1,2);
		isStarted = false;
	}
	@Override
	public Step getLastStep() {
		// TODO Auto-generated method stub
		return lastStep;
	}

	@Override
	public boolean makeStep(Step myStep) {
		// TODO Auto-generated method stub
		if (lastStep.team == myStep.team) return false;
		if (board[myStep.row][myStep.col] == 0) {
			board[myStep.row][myStep.col] = myStep.team;
			return true;
		}
		else return false;
	}

	@Override
	public boolean isStarted() {
		// TODO Auto-generated method stub
		return isStarted;
	}

	@Override
	public int isEnded() {
		// TODO Auto-generated method stub
		for (int i=0; i<3; i++)
			if ((board[i][0] == board[i][1]) && (board[i][1] == board[i][2]) && (board[i][0] != 0)) return board[i][0];
		for (int i=0; i<3; i++)
			if ((board[0][i] == board[1][i]) && (board[1][i] == board[2][i]) && (board[0][i] != 0)) return board[0][i];
		if ((board[0][0] == board[1][1]) && (board[1][1] == board[2][2]) && (board[0][0] != 0)) return board[0][0];
		if ((board[0][2] == board[1][1]) && (board[1][1] == board[2][0]) && (board[0][2] != 0)) return board[0][2];
		return 0;
	}

	@Override
	public int getId() {
		// TODO Auto-generated method stub
		return id;
	}
	
	@Override
	public void start() {
		// TODO Auto-generated method stub
		isStarted = true;
	}

}
